<template>
  <div class="login-container">
    <!-- 视频背景 -->
    <video
      class="bg-video"
      src="https://www.pexels.com/zh-cn/download/video/6853337/"
      autoplay
      loop
      muted
      playsinline
      poster="https://picsum.photos/id/1042/1920/1080"
    ></video>

    <!-- 半透明遮罩 -->
    <div class="bg-overlay"></div>

    <!-- 登录内容 -->
    <div class="login-content">
      <!-- 品牌区 -->
      <div class="brand-section">
        <div class="brand-title">
          <i class="fa fa-music"></i> MelodyAI
        </div>
        <p>释放AI的音乐创造力</p>
      </div>

      <!-- 登录表单 -->
      <div class="form-card">
        <!-- 页面内消息提示 -->
        <div 
          class="message提示" 
          :class="{ success: message.type === 'success', error: message.type === 'error' }"
          v-if="message.show"
        >
          {{ message.text }}
        </div>

        <h2>{{ isLogin ? '登录' : '注册' }}</h2>

        <!-- 手机号输入 -->
        <div class="form-item">
          <label>手机号</label>
          <input 
            type="tel" 
            v-model="form.phone" 
            placeholder="请输入11位手机号"
            class="input"
            maxlength="11"
          >
          <p class="error">{{ errors.phone }}</p>
        </div>

        <!-- 短信验证码（仅注册） -->
        <div v-if="!isLogin" class="form-item">
          <label>短信验证码</label>
          <div class="verify-code-row">
            <input 
              type="text" 
              v-model="form.verifyCode" 
              placeholder="请输入6位验证码"
              class="input verify-code-input"
              maxlength="6"
            >
            <button 
              @click="sendVerifyCode" 
              class="verify-code-btn"
              :disabled="isCodeBtnDisabled"  
              :class="{ disabled: isCodeBtnDisabled }"  
            >
              {{ countdown > 0 ? `${countdown}s重发` : '获取验证码' }}
            </button>
          </div>
          <p class="error">{{ errors.verifyCode }}</p>
        </div>

        <!-- 密码输入 -->
        <div class="form-item">
          <label>密码</label>
          <div class="password-wrap">
            <input 
              :type="showPwd ? 'text' : 'password'" 
              v-model="form.password" 
              placeholder="请输入密码"
              class="input"
            >
            <button @click="showPwd = !showPwd" class="toggle-btn">
              {{ showPwd ? '隐藏' : '显示' }}
            </button>
          </div>
          <p class="error">{{ errors.password }}</p>
        </div>

        <!-- 确认密码（仅注册） -->
        <div v-if="!isLogin" class="form-item">
          <label>确认密码</label>
          <div class="password-wrap">
            <input 
              :type="showConfirmPwd ? 'text' : 'password'" 
              v-model="form.confirmPwd" 
              placeholder="请再次输入密码"
              class="input"
            >
            <button @click="showConfirmPwd = !showConfirmPwd" class="toggle-btn">
              {{ showConfirmPwd ? '隐藏' : '显示' }}
            </button>
          </div>
          <p class="error">{{ errors.confirmPwd }}</p>
        </div>

        <!-- 提交按钮 -->
        <button 
          class="submit-btn" 
          :disabled="loading"
          @click="submit"
        >
          {{ loading ? '处理中...' : (isLogin ? '登录' : '注册') }}
        </button>

        <!-- 切换模式 + 忘记密码入口 -->
        <div class="mode-group">
          <div class="toggle-mode" @click="toggleMode">
            {{ isLogin ? '没有账号？注册' : '已有账号？登录' }}
          </div>
          <div 
            class="forgot-password" 
            @click="showForgotPwd = true"
            v-if="isLogin"
          >
            忘记密码？
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 忘记密码弹窗 -->
  <div class="modal-overlay" v-if="showForgotPwd">
    <div class="forgot-pwd-modal">
      <!-- 忘记密码弹窗内的消息提示 -->
      <div 
        class="message提示" 
        :class="{ success: forgotMessage.type === 'success', error: forgotMessage.type === 'error' }"
        v-if="forgotMessage.show"
      >
        {{ forgotMessage.text }}
      </div>

      <h3>找回密码</h3>
      <button class="close-btn" @click="showForgotPwd = false">×</button>

      <div class="form-item">
        <label>手机号</label>
        <input 
          type="tel" 
          v-model="forgotForm.phone" 
          placeholder="请输入绑定的手机号"
          class="input"
          maxlength="11"
        >
        <p class="error">{{ forgotErrors.phone }}</p>
      </div>

      <div class="form-item">
        <label>短信验证码</label>
        <div class="verify-code-row">
          <input 
            type="text" 
            v-model="forgotForm.verifyCode" 
            placeholder="请输入6位验证码"
            class="input verify-code-input"
            maxlength="6"
          >
          <button 
            @click="sendForgotVerifyCode" 
            class="verify-code-btn"
            :disabled="isForgotCodeBtnDisabled"
            :class="{ disabled: isForgotCodeBtnDisabled }"
          >
            {{ forgotCountdown > 0 ? `${forgotCountdown}s重发` : '获取验证码' }}
          </button>
        </div>
        <p class="error">{{ forgotErrors.verifyCode }}</p>
      </div>

      <div class="form-item">
        <label>新密码</label>
        <div class="password-wrap">
          <input 
            :type="showForgotNewPwd ? 'text' : 'password'" 
            v-model="forgotForm.newPwd" 
            placeholder="请输入新密码"
            class="input"
          >
          <button @click="showForgotNewPwd = !showForgotNewPwd" class="toggle-btn">
            {{ showForgotNewPwd ? '隐藏' : '显示' }}
          </button>
        </div>
        <p class="error">{{ forgotErrors.newPwd }}</p>
      </div>

      <div class="form-item">
        <label>确认新密码</label>
        <div class="password-wrap">
          <input 
            :type="showForgotConfirmPwd ? 'text' : 'password'" 
            v-model="forgotForm.confirmNewPwd" 
            placeholder="请再次输入新密码"
            class="input"
          >
          <button @click="showForgotConfirmPwd = !showForgotConfirmPwd" class="toggle-btn">
            {{ showForgotConfirmPwd ? '隐藏' : '显示' }}
          </button>
        </div>
        <p class="error">{{ forgotErrors.confirmNewPwd }}</p>
      </div>

      <button 
        class="submit-btn" 
        :disabled="forgotLoading"
        @click="submitForgotPwd"
      >
        {{ forgotLoading ? '处理中...' : '重置密码' }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onUnmounted, watch, computed } from 'vue';
import request from '@/utils/request';
import { useRouter } from 'vue-router';

const router = useRouter();

// 消息提示相关
const message = reactive({
  show: false,
  text: '',
  type: 'success'
});
let messageTimer = null;

// 忘记密码弹窗内的消息提示
const forgotMessage = reactive({
  show: false,
  text: '',
  type: 'success'
});
let forgotMessageTimer = null;

// 清除定时器
const clearTimers = () => {
  if (messageTimer) clearTimeout(messageTimer);
  if (forgotMessageTimer) clearTimeout(forgotMessageTimer);
};

// 显示消息提示
const showMessage = (msg, type = 'success', duration = 3000, target = message) => {
  target.show = true;
  target.text = msg;
  target.type = type;
  clearTimers();
  const timer = setTimeout(() => {
    target.show = false;
  }, duration);
  if (target === message) {
    messageTimer = timer;
  } else {
    forgotMessageTimer = timer;
  }
};

// 状态管理
const isLogin = ref(true);
const loading = ref(false);
const showPwd = ref(false);
const showConfirmPwd = ref(false);
const countdown = ref(0); // 验证码倒计时（秒）
const codeTimer = ref(null); // 存储验证码定时器
const forgotLoading = ref(false);

// 表单数据
const form = reactive({
  phone: '',
  verifyCode: '',
  password: '',
  confirmPwd: ''
});

// 错误信息
const errors = reactive({
  phone: '',
  verifyCode: '',
  password: '',
  confirmPwd: ''
});

// 计算属性：验证码按钮是否禁用（核心）
const isCodeBtnDisabled = computed(() => {
  // 只要倒计时大于0，就禁用按钮
  return countdown.value > 0 || !form.phone.trim();
});

// 忘记密码相关状态
const showForgotPwd = ref(false);
const showForgotNewPwd = ref(false);
const showForgotConfirmPwd = ref(false);
const forgotCountdown = ref(0);
const forgotCodeTimer = ref(null);

// 忘记密码表单数据
const forgotForm = reactive({
  phone: '',
  verifyCode: '',
  newPwd: '',
  confirmNewPwd: ''
});

// 忘记密码错误信息
const forgotErrors = reactive({
  phone: '',
  verifyCode: '',
  newPwd: '',
  confirmNewPwd: ''
});

// 忘记密码验证码按钮是否禁用
const isForgotCodeBtnDisabled = computed(() => {
  return forgotCountdown.value > 0 || !forgotForm.phone.trim();
});

// 切换登录/注册模式
const toggleMode = () => {
  isLogin.value = !isLogin.value;
  // 重置表单和状态
  Object.keys(form).forEach(k => form[k] = '');
  Object.keys(errors).forEach(k => errors[k] = '');
  if (codeTimer.value) {
    clearInterval(codeTimer.value);
    codeTimer.value = null;
  }
  countdown.value = 0;
  message.show = false;
};

// 发送验证码（核心修复版）
const sendVerifyCode = async () => {
  // 1. 手机号验证
  const phoneReg = /^1[3-9]\d{9}$/;
  if (!phoneReg.test(form.phone)) {
    errors.phone = '请输入正确的11位手机号';
    return;
  }
  errors.phone = '';

  // 2. 立即启动倒计时，禁用按钮（无论接口是否成功）
  countdown.value = 60;
  
  // 3. 清除可能存在的旧定时器
  if (codeTimer.value) {
    clearInterval(codeTimer.value);
  }
  
  // 4. 设置新定时器
  codeTimer.value = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(codeTimer.value);
      codeTimer.value = null;
    }
  }, 1000);

  // 5. 调用接口（即使接口失败，倒计时仍会继续）
  try {
    const res = await request.post('/send-sms', { phone: form.phone });
    console.log(res)

    if (res.code == 1) {
      showMessage('验证码已发送，请查收短信');
    } else {
      errors.verifyCode = res.msg || '验证码发送失败，60秒后可重试';
    }
  } catch (error) {
    console.error('发送验证码错误：', error);
    errors.verifyCode = '网络异常，请稍后重试';
  }
};

// 登录/注册提交
const submit = async () => {
  let valid = true;
  Object.keys(errors).forEach(k => errors[k] = '');
  const phoneReg = /^1[3-9]\d{9}$/;

  // 1. 手机号校验
  if (!form.phone.trim()) {
    errors.phone = '请输入手机号';
    valid = false;
  } else if (!phoneReg.test(form.phone)) {
    errors.phone = '请输入正确的11位手机号';
    valid = false;
  }

  // 2. 验证码校验（仅注册）
  if (!isLogin.value) {
    if (!form.verifyCode.trim()) {
      errors.verifyCode = '请输入验证码';
      valid = false;
    } else if (!/^\d{6}$/.test(form.verifyCode)) {
      errors.verifyCode = '验证码需为6位数字';
      valid = false;
    }
  }

  // 3. 密码校验
  if (!form.password.trim()) {
    errors.password = '请输入密码';
    valid = false;
  } else if (form.password.length < 6) {
    errors.password = '密码至少6位字符';
    valid = false;
  }

  // 4. 确认密码校验（仅注册）
  if (!isLogin.value) {
    if (!form.confirmPwd.trim()) {
      errors.confirmPwd = '请确认密码';
      valid = false;
    } else if (form.password !== form.confirmPwd) {
      errors.confirmPwd = '两次输入的密码不一致';
      valid = false;
    }
  }

  if (valid) {
    loading.value = true;
    try {
      if (isLogin.value) {
        const data = await request.post('/login', {
          phone: form.phone,
          password: form.password
        });
        const { token, userInfo } = data.data || {};
        if (token && userInfo) {
          localStorage.setItem('userToken', token);
          localStorage.setItem('currentUser', JSON.stringify(userInfo));
          showMessage('登录成功，即将跳转到首页');
          setTimeout(() => router.push('/home'), 1500);
        } else {
          errors.password = '登录失败，请检查账号密码';
        }
      } else {
        const res = await request.post('/register', {
          phone: form.phone,
          verifyCode: form.verifyCode,
          password: form.password
        });
        if (res.code == 1) {
          showMessage('注册成功，请登录');
          setTimeout(() => toggleMode(), 1500);
        } else {
          errors.verifyCode = res?.msg || '注册失败，请重试';
        }
      }
    } catch (error) {
      console.error('提交错误：', error);
      errors.password = '网络异常，请重试';
    } finally {
      loading.value = false;
    }
  }
};

// 忘记密码-发送验证码
const sendForgotVerifyCode = async () => {
  const phoneReg = /^1[3-9]\d{9}$/;
  if (!phoneReg.test(forgotForm.phone)) {
    forgotErrors.phone = '请输入正确的11位手机号';
    return;
  }
  forgotErrors.phone = '';

  // 立即启动倒计时
  forgotCountdown.value = 60;
  if (forgotCodeTimer.value) {
    clearInterval(forgotCodeTimer.value);
  }
  forgotCodeTimer.value = setInterval(() => {
    forgotCountdown.value--;
    if (forgotCountdown.value <= 0) {
      clearInterval(forgotCodeTimer.value);
      forgotCodeTimer.value = null;
    }
  }, 1000);

  try {
    const res = await request.post('/send-forgot-sms', { phone: forgotForm.phone });
    if (res.code == 1) {
      showMessage('验证码已发送，请查收短信', 'success', 3000, forgotMessage);
    } else {
      forgotErrors.verifyCode = res?.msg || '发送失败，60秒后可重试';
    }
  } catch (error) {
    console.error('发送验证码错误：', error);
    forgotErrors.verifyCode = '发送失败，60秒后可重试';
  }
};

// 忘记密码-提交重置
const submitForgotPwd = async () => {
  let valid = true;
  Object.keys(forgotErrors).forEach(k => forgotErrors[k] = '');
  const phoneReg = /^1[3-9]\d{9}$/;

  if (!forgotForm.phone.trim()) {
    forgotErrors.phone = '请输入手机号';
    valid = false;
  } else if (!phoneReg.test(forgotForm.phone)) {
    forgotErrors.phone = '请输入正确的11位手机号';
    valid = false;
  }
  if (!forgotForm.verifyCode.trim()) {
    forgotErrors.verifyCode = '请输入验证码';
    valid = false;
  } else if (!/^\d{6}$/.test(forgotForm.verifyCode)) {
    forgotErrors.verifyCode = '验证码需为6位数字';
    valid = false;
  }
  if (!forgotForm.newPwd.trim()) {
    forgotErrors.newPwd = '请输入新密码';
    valid = false;
  } else if (forgotForm.newPwd.length < 6) {
    forgotErrors.newPwd = '密码至少6位';
    valid = false;
  }
  if (forgotForm.newPwd !== forgotForm.confirmNewPwd) {
    forgotErrors.confirmNewPwd = '两次密码不一致';
    valid = false;
  }

  if (valid) {
    forgotLoading.value = true;
    try {
      const res = await request.post('/forgot-password', {
        phone: forgotForm.phone,
        verifyCode: forgotForm.verifyCode,
        password: forgotForm.newPwd
      });
      if (res.code == 1) {
        showMessage('密码重置成功，请登录', 'success', 3000, forgotMessage);
        setTimeout(() => {
          showForgotPwd.value = false;
          Object.keys(forgotForm).forEach(k => forgotForm[k] = '');
        }, 1500);
      } else {
        forgotErrors.verifyCode = res?.msg || '重置失败，请重试';
      }
    } catch (error) {
      console.error('重置密码错误：', error);
      forgotErrors.verifyCode = '网络异常，请重试';
    } finally {
      forgotLoading.value = false;
    }
  }
};

// 实时监听确认密码
watch(
  () => form.confirmPwd,
  (newVal) => {
    if (!isLogin.value && form.password.trim() && newVal.trim()) {
      errors.confirmPwd = form.password !== newVal ? '两次输入的密码不一致' : '';
    }
  }
);

// 组件卸载时清理定时器
onUnmounted(() => {
  clearTimers();
  if (codeTimer.value) clearInterval(codeTimer.value);
  if (forgotCodeTimer.value) clearInterval(forgotCodeTimer.value);
});
</script>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: sans-serif;
}

.login-container {
  width: 100vw;
  height: 100vh;
  position: relative;
  overflow: hidden;
}

.bg-video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  opacity: 0.6;
  z-index: 1;
}

.bg-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #0f172a;
  opacity: 0.8;
  z-index: 2;
}

.login-content {
  position: relative;
  z-index: 3;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  color: white;
}

.brand-section {
  margin-bottom: 30px;
  text-align: center;
}
.brand-title {
  font-size: 28px;
  margin-bottom: 10px;
}

.form-card {
  width: 100%;
  max-width: 360px;
  padding: 25px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 10px;
}
.form-card h2 {
  text-align: center;
  margin-bottom: 20px;
}

/* 消息提示样式 */
.消息提示 {
  padding: 10px;
  border-radius: 5px;
  margin-bottom: 15px;
  text-align: center;
  font-size: 14px;
  transition: opacity 0.3s;
}
.消息提示.success {
  background: rgba(72, 187, 120, 0.2);
  color: #48bb78;
  border: 1px solid #48bb78;
}
.消息提示.error {
  background: rgba(239, 68, 68, 0.2);
  color: #ef4444;
  border: 1px solid #ef4444;
}

.form-item {
  margin-bottom: 15px;
}
.form-item label {
  display: block;
  margin-bottom: 5px;
  font-size: 14px;
  color: #ddd;
}
.input {
  width: 100%;
  padding: 10px;
  border: 1px solid #444;
  border-radius: 5px;
  background: rgba(255, 255, 255, 0.1);
  color: white;
  outline: none;
}

.verify-code-row {
  display: flex;
  gap: 10px;
  align-items: center;
}
.verify-code-input {
  flex: 1;
}
.verify-code-btn {
  padding: 0 12px;
  height: 42px;
  border: 1px solid #444;
  border-radius: 5px;
  background: #6366f1;
  color: white;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s;
}
/* 禁用状态样式 - 确保完全无法点击 */
.verify-code-btn.disabled {
  background: #444;
  color: #888;
  cursor: not-allowed;
  pointer-events: none; /* 核心：禁止所有鼠标事件 */
  opacity: 0.7;
  transform: none;
  box-shadow: none;
}

.password-wrap {
  position: relative;
}
.toggle-btn {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  background: transparent;
  border: none;
  color: #aaa;
  font-size: 12px;
  cursor: pointer;
}

.error {
  color: #ff6b6b;
  font-size: 12px;
  margin-top: 3px;
}

.submit-btn {
  width: 100%;
  padding: 10px;
  background: #6366f1;
  border: none;
  border-radius: 5px;
  color: white;
  cursor: pointer;
  margin-bottom: 15px;
}
.submit-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  pointer-events: none;
}

.mode-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.toggle-mode {
  color: #93c5fd;
  cursor: pointer;
}

.forgot-password {
  color: #6366f1;
  cursor: pointer;
}
.forgot-password:hover {
  text-decoration: underline;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
  padding: 20px;
}

.forgot-pwd-modal {
  width: 100%;
  max-width: 360px;
  padding: 25px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 10px;
  position: relative;
}

.forgot-pwd-modal h3 {
  text-align: center;
  margin-bottom: 20px;
  color: white;
}

.close-btn {
  position: absolute;
  top: 15px;
  right: 15px;
  background: transparent;
  border: none;
  color: #aaa;
  font-size: 18px;
  cursor: pointer;
}
.close-btn:hover {
  color: white;
}

@media (min-width: 768px) {
  .login-content {
    flex-direction: row;
    gap: 50px;
  }
  .brand-section {
    margin-bottom: 0;
  }
}
</style>
